package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.utils.threadlocal.AppThreadLocalUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName ApLikesBehaviorServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/22 22:06
 * @Version 1.0
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Resource
    private ApBehaviorEntryService apBehaviorEntryService;

    /**
     * @param dto 点赞行为对象
     * @return 保存结果
     * @Description 保存点赞行为
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (ObjectUtils.isEmpty(apBehaviorEntry)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApLikesBehavior apLikesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId()));
        // 保存点赞
        if (ObjectUtils.isEmpty(apLikesBehavior) && dto.getOperation().equals(ApLikesBehavior.Operation.LIKE.getCode())) {
            apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setOperation(dto.getOperation());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setEntryId(apBehaviorEntry.getId());
            save(apLikesBehavior);
        } else {
            //4.取消点赞/点赞
            apLikesBehavior.setOperation(dto.getOperation());
            updateById(apLikesBehavior);
        }
        return ResponseResult.okResult();
    }
}
